package com.ph.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ph.pojo.Permission;
import com.ph.pojo.RolePermission;
import com.ph.mapper.PermissionMapper;
import com.ph.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Override
    public List<Permission> permissionTree( Integer roleId) {
       return baseMapper.findByTree(0, roleId);
    }

    @Override
    public boolean checkPermission(RolePermission rolePermission) {
        if (baseMapper.checkPermission(rolePermission.getRid(),rolePermission.getPid())){
            baseMapper.deleteCheckPermission(rolePermission.getRid(),rolePermission.getPid());
            return false;
        }else {
            baseMapper.addCheckPermission(rolePermission.getRid(),rolePermission.getPid());
            return true;
        }
    }

    @Override
    public boolean checkParentPermission(RolePermission rolePermission) {
//        if (rolePermission == null) {
//            throw new IllegalArgumentException("RolePermission cannot be null");
//        }
//        if (rolePermission.getRid() == null || rolePermission.getPid() == null) {
//            throw new IllegalArgumentException("Rid or Pid cannot be null");
//        }
//        log.info("{}" , rolePermission);
        baseMapper.deleteParentPermission(rolePermission.getRid(),rolePermission.getPid());
        if (rolePermission.getChecked()){
            List<Integer> ids = baseMapper.findPermissionIdsByParentId(rolePermission.getPid());
            for (Integer id : ids){
                baseMapper.addCheckPermission(rolePermission.getRid(),id);
            }
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Permission> findLevel1ByUserId() {
        Integer userId = (Integer) SecurityUtils.getSubject().getPrincipal();
        return baseMapper.findLevel1ByUserId(userId);
    }
}
